import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Tab, Dropdown, Menu, Badge } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import {
  Header,
  Body,
  BodyContent,
  OperationBar,
  Content,
  SearchIcon,
  ButtonIcon,
  YunxiaoList,
} from '@alife/devops-ui';
import MrSkeleton from 'components/skeleton/mr';
import CrListItem from 'components/crListItem';
import track, { enterPage, Perf } from 'utils/track';
import ListEmpty from 'atComponents/ListEmpty';
import debounce from 'lodash.debounce';
import CrAdvancedSearch from 'components/crAdvancedSearch';
import GitRepoTip from 'components/gitRepoTip';
import * as actions from '../actions/index';
import KEYCODE from 'utils/keycode';
import docs from 'utils/docs';
import { ENUM } from 'utils/constants';
import intl from '../../../../../../../locale';

const { ctrlKey, ctrlTxt } = ENUM.getOSKeyMap();

class Root extends Component {
  static propTypes = {
    tabKey: PropTypes.string,
    orderKey: PropTypes.string,
    mergeRequests: PropTypes.arrayOf(PropTypes.object),
    currentPage: PropTypes.number,
    totalData: PropTypes.number,

    getMergeRequests: PropTypes.func,
    setSearch: PropTypes.func,
    setTabKey: PropTypes.func,
    setOrderKey: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.onSearch = debounce(this.onSearch, 500);
  }

  state = {
    pageSize: 10,
  };

  componentDidMount() {
    // this.props.getMergeRequests(1);
    this.props.setResetList();

    enterPage('Group-MRs', {
      sendPerf: false,
    });

    document.addEventListener('keydown', this.handleKeyCodeEvent);
  }

  handleKeyCodeEvent = (e) => {
    // ctrl + / 进行搜索
    if (e[ctrlKey] && e.keyCode === KEYCODE.SPLIT) {
      document.querySelector('.search-ctrl>button').click();
      document.querySelector('.search-ctrl input').focus();
    }
  };

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyCodeEvent);
  }

  // 搜索条件
  onSearch = (search) => {
    track({
      action: 'search_mr',
      page: 'Repo-MRs',
    });

    this.props.setSearch(search);
  };

  // 排序
  onOrderKeySelect = (orderKey) => {
    this.props.setOrderKey(orderKey.toString());
  };

  // tab切换
  onTabKeySelectChange = (tabKey) => {
    this.props.setTabKey(tabKey);
    this.props.setResetList();
  };

  getTotal = (key) => {
    const { totalData } = this.props;
    return totalData[key];
  };

  onPageNoChange = (page) => {
    const { pageSize } = this.state;
    this.props.getGroupMergeRequests(page, {
      per_page: pageSize,
    });
  };

  onPageSizeChange = (pageSize) => {
    this.setState(
      {
        pageSize,
      },
      () => {
        this.onPageNoChange(1);
      },
    );
  };

  render() {
    const { tabKey, orderKey, currentPage, totalData } = this.props;
    const stateTabDataSource = [
      {
        value: (
          <span>
            {intl.get({
              id: 'code-assets.groupMergeRequest.containers.root.Enabled',
              defaultMessage: '已开启',
            })}
          </span>
        ),

        key: 'opened',
        badge: <Badge count={this.getTotal('opened')} showZero />,
      },

      {
        value: (
          <span>
            {intl.get({
              id: 'code-assets.groupMergeRequest.containers.root.Merged',
              defaultMessage: '已合并',
            })}
          </span>
        ),

        key: 'merged',
        badge: <Badge count={this.getTotal('merged')} showZero />,
      },

      {
        value: (
          <span>
            {intl.get({
              id: 'code-assets.groupMergeRequest.containers.root.Disabled',
              defaultMessage: '已关闭',
            })}
          </span>
        ),

        key: 'closed',
        badge: <Badge count={this.getTotal('closed')} showZero />,
      },

      {
        value: (
          <span>
            {intl.get({
              id: 'code-assets.groupMergeRequest.containers.root.All',
              defaultMessage: '全部',
            })}
          </span>
        ),

        key: 'all',
        badge: <Badge count={this.getTotal('all')} showZero />,
      },
    ];

    return (
      <>
        <Header
          title={intl.get({
            id: 'code-assets.groupMergeRequest.containers.root.MergeRequest',
            defaultMessage: '合并请求',
          })}
          operation={
            <>
              <SearchIcon
                direction="rtl"
                placeholder={intl.get({
                  id: 'code-assets.src.utils.locale.SearchReview',
                  defaultMessage: '搜索评审',
                })}
                onChange={(value) => {
                  this.onSearch(value);
                }}
                defaultValue={this.props.search}
                className="search-ctrl"
                triggerTooltipProps={{
                  children: (
                    <div>
                      {intl.get({
                        id: 'code-assets.groupMergeRequest.containers.root.Search',
                        defaultMessage: '搜索',
                      })}
                      <br />
                      {ctrlTxt} + /
                    </div>
                  ),

                  align: 't',
                }}
              />

              <CrAdvancedSearch {...this.props} />
              <Dropdown trigger={<ButtonIcon name="sort-line" />} triggerType="click" align="tr br">
                <Menu onSelect={this.onOrderKeySelect} selectMode="single" selectedKeys={orderKey}>
                  <Menu.Item
                    key="updated_at"
                    onClick={() => {
                      track({
                        action: 'sort_by_update',
                        page: 'Repo-MRs',
                      });
                    }}
                  >
                    {intl.get({
                      id: 'code-assets.groupMergeRequest.containers.root.UpdateTime',
                      defaultMessage: '更新时间',
                    })}
                  </Menu.Item>
                  <Menu.Item
                    key="created_at"
                    onClick={() => {
                      track({
                        action: 'sort_by_create',
                        page: 'Repo-MRs',
                      });
                    }}
                  >
                    {intl.get({
                      id: 'code-assets.groupMergeRequest.containers.root.Created',
                      defaultMessage: '创建时间',
                    })}
                  </Menu.Item>
                </Menu>
              </Dropdown>
            </>
          }
        />

        <Body className="groupMerge-container-root">
          <BodyContent>
            <OperationBar>
              <Tab onChange={this.onTabKeySelectChange} activeKey={tabKey} animation={false}>
                {stateTabDataSource.map((item) => (
                  <Tab.Item
                    title={
                      <span className="title-span-badge">
                        <span>{item.value}</span>
                        {item.badge}
                      </span>
                    }
                    key={item.key}
                  />
                ))}
              </Tab>
            </OperationBar>
            <Content>{this.renderList()}</Content>
            <Pagination
              onChange={this.onPageNoChange}
              current={currentPage}
              total={totalData[tabKey]}
              pageSize={this.state.pageSize}
              onPageSizeChange={this.onPageSizeChange}
              footerProps={{
                left: <GitRepoTip />,
              }}
            />
          </BodyContent>
        </Body>
      </>
    );
  }

  mergeEmptyhander = () => {
    return (
      <div>
        <p>
          {intl.get({
            id: 'code-assets.groupMergeRequest.containers.root.InitiateMergeRequestsToEnsure',
            defaultMessage: '发起合并请求，保障代码质量，展开代码协作吧',
          })}
        </p>
        <a href={docs('mr_intro')} target="_blank " rel="noreferrer">
          {intl.get({
            id: 'code-assets.groupMergeRequest.containers.root.HowCanIUseMerge',
            defaultMessage: '如何利用合并请求提升代码质量？',
          })}
        </a>
      </div>
    );
  };

  renderEmpty = () => {
    const { search } = this.props;
    return (
      <ListEmpty
        fullPage
        type="project"
        className="no-btns"
        imgType={search ? 'search' : 'none'}
        content={
          search
            ? null
            : intl.get({
                id: 'code-assets.groupMergeRequest.containers.root.NoMergeRequestRecordsAre',
                defaultMessage: '暂无合并请求记录',
              })
        }
        description={
          search
            ? intl.get({
                id: 'code-assets.groupMergeRequest.containers.root.NoSearchResults',
                defaultMessage: '搜索无结果',
              })
            : this.mergeEmptyhander()
        }
      />
    );
  };

  renderList = () => {
    const { mergeRequests, isLoading } = this.props;
    return (
      <React.Fragment>
        {!isLoading ? (
          <>
            {mergeRequests.length === 0 ? (
              this.renderEmpty()
            ) : (
              <YunxiaoList
                dataSource={mergeRequests}
                renderItem={(cr) => <CrListItem codeReview={cr} />}
              />
            )}

            <Perf page="Group-MRs" />
          </>
        ) : (
          <MrSkeleton />
        )}
      </React.Fragment>
    );
  };
}

export default connect(
  (state) => state.group.groupMergeRequest,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
